package cn.dyp.com.getnotification.service;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.dyp.com.getnotification.R;
import cn.dyp.com.getnotification.activity.MainActivity;
import cn.dyp.com.getnotification.util.GetNotifiThread;

/**
 * 获取通知的Service类
 *
 * @author asus
 *
 */
public class NotifiService extends Service {
    public static final String PM25_HIGH = "pm2.5 high";
    public static final String CO2_HIGH = "co2 high";
    public static final String CO2_LOW = "co2 low";
    public static final String LIGHT_HIGH = "light high";
    public static final String LIGHT_LOW = "light low";

    public static final String AIR_TMPER_HIGH = "air tmper high";
    public static final String AIR_TMPER_LOW = "air tmper low";
    public static final String AIR_HUMID_HIGH = "air humid high";
    public static final String AIR_HUMID_LOW = "air humid low";

    public static final String SOIL_TMPER_HIGH = "soil tmper high";
    public static final String SOIL_TMPER_LOW = "soil tmper low";
    public static final String SOIL_HUMID_HIGH = "soil humid high";
    public static final String SOIL_HUMID_LOW = "soil humid low";

    private GetNotifiThread mThread;
    private long mNotifiId = -1;
    private Map<String, Object> mMap;//Map是以键值形式存储数据,有点类似于数组
    private List<Object> mList = new ArrayList<Object>();
    private String marks[];
    private int ids[];
    private Handler mHandler;

    @Override
    public IBinder onBind(Intent arg0) {//绑定
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        handleData();
        initData();
        startGetNotifiThread();
    }

    /**
     * 数据处理
     *
     */
    private void handleData() {
        mHandler = new Handler(new Handler.Callback() {

            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case GetNotifiThread.MSG_NOTIFI_RESULT:
                        handlerNotifiStr((String) msg.obj);
                        break;
                }
                return false;
            }
        });
    }

    /**
     * 处理通知
     *
     * @param notifiStr
     *            通知内容
     */
    private void handlerNotifiStr(String notifiStr) {
        if (notifiStr == null || notifiStr.equals("")) {
            return;
        }
        long id = -1;
        String notifiMsg = "";
        try {
            JSONObject jsonRespObj = new JSONObject(notifiStr);
            if (jsonRespObj != null) {
                if (jsonRespObj.has("notifiId")) {
                    id = jsonRespObj.getLong("notifiId");
                }
                if (jsonRespObj.has("notifiMsg")) {
                    notifiMsg = jsonRespObj.getString("notifiMsg");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (id > -1 && id != mNotifiId) {
            mNotifiId = id;
            setNotification(notifiMsg);
        }
    }

    /**
     * 初始化数据
     *
     */
    private void initData() {
        marks = new String[] { PM25_HIGH, CO2_HIGH, CO2_LOW, LIGHT_HIGH,
                LIGHT_LOW, AIR_TMPER_HIGH, AIR_TMPER_LOW, AIR_HUMID_HIGH,
                AIR_HUMID_LOW, SOIL_TMPER_HIGH, SOIL_TMPER_LOW,
                SOIL_HUMID_HIGH, SOIL_HUMID_LOW };
        ids = new int[] { R.string.pm25_high, R.string.co2_high,
                R.string.co2_low, R.string.light_high, R.string.light_low,
                R.string.air_tmper_high, R.string.air_tmper_low,
                R.string.air_humid_high, R.string.air_humid_low,
                R.string.soil_tmper_high, R.string.soil_tmper_low,
                R.string.soil_humid_high, R.string.soil_humid_low };
        mList.clear();
        int id = 1;
        for (int i = 0; i < marks.length; i++) {
            mMap = new HashMap<String, Object>();
            mMap.put("name", marks[i]);
            mMap.put("num", 0);
            mMap.put("id", id++);
            mMap.put("isFirst", true);
            mList.add(mMap);
        }
    }

    @Override
    public void onDestroy() {
        stopReceiveThread();
        super.onDestroy();
    }

    /**
     * 启动线程
     *
     */
    private void startGetNotifiThread() {
        stopReceiveThread();
        mThread = new GetNotifiThread(getApplicationContext(), mHandler);
        mThread.start();
    }

    /**
     * 关闭线程
     *
     */
    private void stopReceiveThread() {
        if (mThread != null) {
            mThread.stopThread();
            mThread = null;
        }
    }

    /**
     * 创建通知
     *
     * @param message
     *            通知内容
     * @param id
     *            通知Id
     */
    private void showNotificationView(String message, int id, int num) {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this).setSmallIcon((R.mipmap.ic_launcher))
                .setContentTitle(getString(R.string.intelligent_ariculture))
                .setAutoCancel(true).setContentText(message)
                .setWhen(System.currentTimeMillis()).setNumber(num)
                .setDefaults(Notification.DEFAULT_ALL);
        Intent resultIntent = new Intent(this, MainActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(id, mBuilder.build());
    }

    /**
     * 设置通知
     *
     * @param notifiMsg
     *            通知消息
     */
    private void setNotification(String notifiMsg) {
        if (notifiMsg == null) {
            return;
        }
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        for (int i = 0; i < mList.size(); i++) {
            if ((Boolean) ((Map<?, ?>) mList.get(i)).get("isFirst")) {
                mNotificationManager.cancel(i);
                mMap = (Map<String, Object>) mList.get(i);
                mMap.put("num", 0);
                mMap.put("isFirst", true);
            }
        }
        String notifis[] = notifiMsg.split(",");
        for (int j = 0; j < notifis.length; j++) {
            for (int i = 0; i < mList.size(); i++) {
                int num = Integer.valueOf(((Map<?, ?>) mList.get(i)).get("num")
                        .toString());
                int mId = Integer.valueOf(((Map<?, ?>) mList.get(i)).get("id")
                        .toString());
                if (notifis[j].equals(((Map<?, ?>) mList.get(i)).get("name"))) {
                    showNotificationView(getString(ids[i - 1]), mId, ++num);
                    mMap = (Map<String, Object>) mList.get(i);
                    mMap.put("num", String.valueOf(num));
                    mMap.put("isFirst", false);
                    break;
                }
            }
        }
    }
}
